import { app, BrowserWindow } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";
import windowStateKeeper from "electron-window-state";
import { registerWindowHolder } from "@electron/main/ipc-service/window-holder";
import { registerWindowIpcService } from "./main/ipc-service/window-ipc-service";
import { registerDialogService } from "./main/ipc-service/dialog-service";
import "./main/ipc-service/archive-file-service";
import "./main/ipc-service/file-service";
import "./main/ipc-service/http-service";
import "./main/ipc-service/cp-service";
import "./main/ipc-service/shell-service";
import "./main/ipc-service/spider-service";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, "..");
// 禁用安全警告
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "true";

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");
const IS_DEV = process.env.NODE_ENV === "development";

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, "public") : RENDERER_DIST;

let mainWindow: BrowserWindow | null;

function stateKeeper() {
  return windowStateKeeper({
    defaultWidth: 1366,
    defaultHeight: 768,
    maximize: true,
  });
}

function createMainWindow(state: windowStateKeeper.State) {
  mainWindow = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, "favicon.ico"),
    center: true,
    width: state.width,
    height: state.height,
    x: state.x,
    y: state.y,
    minWidth: 1366,
    minHeight: 768,
    // frame: false,
    title: "开发环境管理",
    // useContentSize: true,
    titleBarStyle: "hidden",
    // titleBarOverlay: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: true,
    },
  });
  registerWindowHolder(mainWindow);
  registerWindowIpcService(mainWindow);
  registerDialogService(mainWindow);

  // 删除默认菜单
  mainWindow.removeMenu();
  // 管理窗口状态
  state.manage(mainWindow);

  mainWindow.webContents.on("did-finish-load", () => {
    // 前端加载完成
    if (IS_DEV) {
      mainWindow!.webContents.openDevTools({ mode: "detach" });
    }
  });

  if (VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(VITE_DEV_SERVER_URL).catch(() => void 0);
    // mainWindow.loadURL("https://www.antdv.com/components/date-picker-cn").catch(() => void 0);
  } else {
    // win.loadFile('dist/index.html')
    mainWindow.loadFile(path.join(RENDERER_DIST, "index.html")).catch(() => void 0);
  }
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    mainWindow = null;
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createMainWindow(stateKeeper());
  }
});

app.on("quit", () => {});

app.whenReady().then(async () => {
  createMainWindow(stateKeeper());
});
